package com.wz.spider;

import java.awt.RenderingHints.Key;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import com.wz.util.DateUtils;
import com.wz.util.KeyBoard;
import com.wz.util.StringUtil;

public class HttpClientUtil {
	private static RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000).setConnectionRequestTimeout(15000).build();

	/** 
     * 发送Get请求Https 
     * @param httpPost 
     * @return 
     */  
	private static String sendHttpsGet(String url, CookieStore cookieStore) {
		HttpClient httpClient = null;
		HttpEntity entity = null;
		HttpResponse response;
		try {
			// 创建默认的httpClient实例.  
			httpClient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
			// 执行请求  
			response = httpClient.execute(new HttpGet(url));
			entity = response.getEntity();
			return EntityUtils.toString(entity, "UTF-8");
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

    private static String sendHttpsPost(HttpPost httpPost, CookieStore cookieStore) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例.  
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpPost.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).setDefaultCookieStore(cookieStore).build();
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPost);
            for (Header head : response.getHeaders("Set-Cookie")) {
            	System.out.println(head.getValue());
			}
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * get response
     * @param httpPost
     * @param cookieStore
     * @return
     */
    private static CloseableHttpResponse doPost(HttpPost httpPost, CookieStore cookieStore) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            // 创建默认的httpClient实例.  
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpPost.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).setDefaultCookieStore(cookieStore).build();
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return response;
    }
    
    private static HttpResponse sendResponseHttpsPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        try {
            // 创建默认的httpClient实例.  
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader.load(new URL(httpPost.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpPost.setConfig(requestConfig);
            // 执行请求
            return httpClient.execute(httpPost);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                // 关闭连接,释放资源
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
  
    //下载验证码图片
    public static void downLoadPic(String url, CookieStore cookieStore){
    	String destfilename = "D:\\GitRes\\Trailplant\\trialplant-proj\\trialplant-core\\temp\\temp.jpg";
    	HttpClient httpclient = HttpClients.custom().setDefaultCookieStore(cookieStore).build();
    	
    	HttpGet httpget = new HttpGet(url);
    	File file = new File(destfilename);
    	if (file.exists()) {
    		file.delete();
    	}

    	HttpResponse response;
    	try {
    		response = httpclient.execute(httpget);
    		HttpEntity entity = response.getEntity();
    		InputStream in = entity.getContent();
    		FileOutputStream fout = new FileOutputStream(file);
    		int l = -1;
    		byte[] tmp = new byte[2048];
    		while ((l = in.read(tmp)) != -1) {
    			fout.write(tmp);
    		}
    		fout.close();
    		in.close();
    	} catch (Exception e) {
    		e.printStackTrace();
    	}
    	httpget.releaseConnection();
    }
    
    
    private void test1(){
//      <input type="hidden" name="_SysTokenName" value="w6zxr7" />
//      <input name="language" type="hidden"  value="gb"/>
//      <input name="LoginType" type="hidden" id="LoginType" value="Z"/>
//      <input name="LoginMode" type="hidden" value="E"/>
//      <input name="Reserve" type="hidden" value=""/>
//      <input name="selectedAuthType" type="hidden"/>
//      <input name="utility" type="hidden" value="" />
//      <input name="signature" type="hidden" id="signature3" value="" />
//      <input name="cn" type="hidden" value="invalid" />
//      <input name="CifNo" type="hidden" value=""/>
//      <input name="CustomerName" type="hidden" value=""/>
//      <input name="isOldCertUser" type="hidden" value=""/>
//      <input name="spflag" type="hidden"/>
//      
//      <!-- InstanceEndEditable hidden field -->
//   
//      <input type="hidden" name="_viewReferer" value="default,popLogin"> 
//  	HttpGet http = new HttpGet("https://ebank.spdb.com.cn/nbper/logindispatch.do?_SysTokenName=w6zxr7&language=gb&LoginType=Z&Password=kljlkjdf&LoginId=ssf243");
//  	System.out.println(sendHttpsGet(http));
  	
  	BasicClientCookie basicClientCookie = new BasicClientCookie("loginModel", "E");
  	basicClientCookie.setAttribute("nbperJsessionId", "1yPbYh1ZDGRhn35vW1vPwLpp74MHwkLR7Ds271pV1jMxc535Q81v!-1153037170");
  	basicClientCookie.setAttribute("SPDB_NET_SESSIONID", "MC4ZYhrNGG82nzcB0vThNntrn6Vpr1mFvkk1SDmpMG26hNhKryhP!2025818055");
  	basicClientCookie.setDomain("https://ebank.spdb.com.cn");
  	basicClientCookie.setPath("https://ebank.spdb.com.cn");
  	BasicCookieStore cookieStore = new BasicCookieStore();
  	cookieStore.addCookie(basicClientCookie);

  	HttpPost post = new HttpPost("https://ebank.spdb.com.cn/nbper/logindispatch.do");
  	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
  	nameValuePairs.add(new BasicNameValuePair("_SysTokenName", "5jgx7p"));
  	nameValuePairs.add(new BasicNameValuePair("language", "gb"));
  	nameValuePairs.add(new BasicNameValuePair("LoginType", "Z"));
  	nameValuePairs.add(new BasicNameValuePair("Password", "MDAwMDAxNDABAgAAAWgAAACkAAD6uBYWVgCNCxrNoRFqaU6rA20vQUAHGHRI7Hv+7oUzqNlRUhLgR8qdPFyglnpQjTc2i9h+pP5qFRXVcqIkRN1rcETwXLJ/Uuczkg1Bamrz8LgNrsJ9CflbPbb6tgb5jlnzXyNMhLsILvRBCaJaWppeil3eWU1ReAcmROJ6VzR9eTAwMDAwNTI315xgtixPC74hltoPUbb6xcIxtupuadbAMGbhDvWGTeCNf0EZQpLQ4wJ2fyhXYqP49jHWWSjltVtTWK+lMILXo3qvM5MONLZBb0xhdttl8uczTswf2+32r+79f4HzM1FT007Q4a7zVXumk9XGCtRv8jBCiooIjr5K5vZkO1YcMILyG0apovLs1wGymgRtAgPaxAe1FgqzcAbOkSJWFgjp4uFeOb14jm/yHjogAUsZjhkqhP5lNxeRDoSvq6GRABV1IcqaR/+b9QZ7ZJHQXskhOUCwzCAtZE3tNmlE9Utw9SO1OpqcNof53zkdYLl+6aZdcQer4HHNcTPhdHXp8bRF6cXGRwBNLFFhRrYPdgS9RkiFpYKkqObg9RgpmbQniZIjhw/dqn1rYmIJW1CT/n7gc5ZFV4L2BEQyljNJxXt6PaRINeRGVfPFTx2QN3+UhV/jl4k/5IN3OUQ7zQpqoOmn7AODMj1mxRbGTpdUMiqjUKAvJCyUX1Xc6rL2AoctXKzWLNDk/7IrhFZ8dX69ai3YwNj1BOexXVpJRhf/DmXgoMS4I8/vmkuwpZFmjOBNu/81L3j/3PsE9NYZHVJVfLpExJiS4HR/MaCLaLGLW3w+Q8x/X6t14AqKBp0OiobjCsw4UPOABbTTBeT2iLnofh0M6U+8nvRwNfBD/6/W8MPP6hK4ifjMvMkfCjcYxyR0LQQ="));
  	nameValuePairs.add(new BasicNameValuePair("LoginId", "430682198201257413"));
  	nameValuePairs.add(new BasicNameValuePair("LoginMode", "E"));
  	nameValuePairs.add(new BasicNameValuePair("Reserve", "4"));
  	nameValuePairs.add(new BasicNameValuePair("selectedAuthType", ""));
  	nameValuePairs.add(new BasicNameValuePair("utility", "MDAwMDAxNDABAgAAAWgAAACkAADBAiirnX3hon+CdOf6uVBay8SvXsDtBXqFDwt/kwNmpXyJ6fPEZ65rQbfGjHjbeh1qXPXicm53mVV3Gw6sNwXlpvBoTgcAyzoKJabTxTulkeW2Er/zt8oe2HTEHaIhZZC/INOb5jPZktpZix9hwNisOgPEK4TJNbaTaJpkMwVJaTAwMDAwMDUx+ceH3FDQ7ZXuqzMaQmhp48duS+ukozeEoBOXvMWORndzAxtLhpbzgSbzBTQEteFxyXwd"));
  	nameValuePairs.add(new BasicNameValuePair("signature", ""));
  	nameValuePairs.add(new BasicNameValuePair("cn", "invalid"));
  	nameValuePairs.add(new BasicNameValuePair("CifNo", ""));
  	nameValuePairs.add(new BasicNameValuePair("CustomerName", ""));
  	nameValuePairs.add(new BasicNameValuePair("isOldCertUser", ""));
  	nameValuePairs.add(new BasicNameValuePair("spflag", ""));
  	nameValuePairs.add(new BasicNameValuePair("_viewReferer", "default,popLogin"));
  	nameValuePairs.add(new BasicNameValuePair("navigator", "msie"));
  	nameValuePairs.add(new BasicNameValuePair("Passwordkeytype", "EncryptorPublicKey"));

  	UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
			post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		System.out.println(sendHttpsPost(post, cookieStore));
	
    }
   
    public static void main(String[] args) {
    	BasicCookieStore cookieStore = new BasicCookieStore();
    	List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	HttpPost post = new HttpPost("http://i.baimao.com/user/center/reg");
    	UrlEncodedFormEntity entity;
		try {
			entity = new UrlEncodedFormEntity(nameValuePairs, "UTF-8");
			post.setEntity(entity);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
//		System.out.println(sendHttpsPost(post, cookieStore));
		CloseableHttpResponse closeableHttpResponse = doPost(post, cookieStore);
		
		String sessionid = "";
//		String expires = "";
//		String path = "";
		String domain = "";
		for (Header head : closeableHttpResponse.getHeaders("Set-Cookie")) {
			Map<String, String> cookies = StringUtil.getCookieParams(head.getValue());
			sessionid = cookies.get("PHPSESSID");
//			expires = cookies.get("expires");
//			path = cookies.get("path");
			domain = cookies.get("domain");
		}

    	BasicClientCookie basicClientCookie = new BasicClientCookie("loginModel", "E");
      	basicClientCookie.setAttribute("PHPSESSID", sessionid);
      	basicClientCookie.setDomain(domain);
//      	basicClientCookie.setPath(path);
//      	basicClientCookie.setExpiryDate(DateUtils.parseDate(expires, "EEE dd-MMM-yyyy hh:mm:ss"));
      	
//      	HttpPost newPost1 = new HttpPost("http://i.baimao.com/user/center/checkcode");
      	BasicCookieStore newCookieStore1 = new BasicCookieStore();
      	newCookieStore1.addCookie(basicClientCookie);
//      	List<NameValuePair> newNameValuePairs = new ArrayList<NameValuePair>();
      	
      	
      	downLoadPic("http://i.baimao.com/user/center/getCaptcha?r=" + Math.random(), newCookieStore1);
      	
      	String captcha = KeyBoard.keyIn();
//      	newNameValuePairs.add(new BasicNameValuePair("captcha", captcha));
      	String url = "http://i.baimao.com/user/center/checkcode?captcha=" + captcha;
      	System.out.println(sendHttpsGet(url, newCookieStore1));
      	
//      	UrlEncodedFormEntity newEntity1;
//		try {
//			newEntity1 = new UrlEncodedFormEntity(newNameValuePairs, "UTF-8");
//			newPost1.setEntity(newEntity1);
//		} catch (UnsupportedEncodingException e) {
//			e.printStackTrace();
//		}
//		System.out.println(sendHttpsPost(newPost1, newCookieStore1));
      	
//      	HttpPost newPost2 = new HttpPost("http://i.baimao.com/user/center/reg/user/center/reg_next");
//      	List<NameValuePair> newNameValuePairs = new ArrayList<NameValuePair>();
//      	newNameValuePairs.add(new BasicNameValuePair("mobi", "13812311112"));
//      	newNameValuePairs.add(new BasicNameValuePair("safecode", "ABCD"));
//      	newNameValuePairs.add(new BasicNameValuePair("agree", "1"));
//      	UrlEncodedFormEntity newEntity;
//    		try {
//    			newEntity = new UrlEncodedFormEntity(newNameValuePairs, "UTF-8");
//    			newPost.setEntity(newEntity);
//    		} catch (UnsupportedEncodingException e) {
//    			e.printStackTrace();
//    		}
//    		System.out.println(sendHttpsPost(newPost, newCookieStore));
    }
}